package archimede;

import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPFile;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
import it.sauronsoftware.ftp4j.FTPListParseException;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.util.Properties;
import java.util.Scanner;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import net.miginfocom.swing.MigLayout;

import org.apache.commons.io.FileUtils;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * Main class, create
 * 
 * @author Alex
 * 
 */
public class StartingWindow {
	/**
	 * frame contenente tutti i pannelli
	 */
	private JFrame window = new JFrame("EUREKA - ARCHIMEDE");
	/**
	 * panel containing tab pages
	 */
	private JPanel projectPanel = new JPanel();
	/**
	 * height of window
	 */
	private int height;
	/**
	 * width of window
	 */
	private int width;

	/**
	 * count RTD
	 */
	private int countRtd = 0;
	/**
	 * nome progetto caricato
	 */
	private String nameProject;

	/**
	 * ultimo percorso aperto per la ricerca di immagini
	 */
	private String lastPath = "";

	/**
	 * tab of pages
	 */
	private JTabbedPane tab = new JTabbedPane();

	/**
	 * menubar contenente i pulsanti APRI , SALVA , PDF , INVIA modificata nel colore e nella forma
	 */
	private JMenuBar menubar = new JMenuBar() {
		/** Stroke size. it is recommended to set it to 1 for better view */
		protected int strokeSize = 1;
		/** Color of shadow */
		protected Color shadowColor = Color.black;
		/** Sets if it drops shadow */
		protected boolean shady = true;
		/** Sets if it has an High Quality view */
		protected boolean highQuality = true;
		/** Double values for Horizzontal and Vertical radius of corner arcs */
		protected Dimension arcs = new Dimension(10, 10);
		/** Distance between border of shadow and border of opaque panel */
		protected int shadowGap = 2;
		/** The offset of shadow. */
		protected int shadowOffset = 4;
		/** The transparency value of shadow. ( 0 - 255) */
		protected int shadowAlpha = 150;

		@Override
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
			int width = getWidth();
			int height = getHeight();
			int shadowGap = this.shadowGap;
			Graphics2D graphics = (Graphics2D) g;

			graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

			// 2 colori che fanno la sfumatura

			Point2D.Float p1 = new Point2D.Float(0.f, 75.f); // Gradient line
																// start
			Point2D.Float p2 = new Point2D.Float(0.f, 0.f); // Gradient line end
			GradientPaint g1 = new GradientPaint(p1, new Color(143, 143, 143), p2, new Color(220, 243, 243), true);
			graphics.setPaint(g1);
			graphics.fillRoundRect(shadowOffset,// X position
					shadowOffset,// Y position
					width - strokeSize - shadowOffset, // width
					height - strokeSize - shadowOffset, // height
					arcs.width, arcs.height);// arc Dimension

			// Draws the rounded opaque panel with borders.

			graphics.fillRoundRect(0, 0, width - shadowGap, height - shadowGap, arcs.width, arcs.height);
			graphics.setColor(getForeground());
			graphics.setStroke(new BasicStroke(strokeSize));

			graphics.drawRoundRect(0, 0, width - shadowGap, height - shadowGap, arcs.width, arcs.height);

			// Sets strokes to default, is better.
			graphics.setStroke(new BasicStroke());
			// graphics.drawString(getText(), 20, 20);
		}
	};

	private JMenu apri = new JMenu("APRI PROGETTO");

	private BuildingData datiEdificio;
	private Premesse premesse;
	private PuntiRilevazione rilevazione;
	private PuntoCritico critico;
	private Piantina piantina;
	private Sali sali;
	private PotenzialiOrizzontali orizzontali;
	private PotenzialiVerticali verticali;
	private Conclusioni conclusioni;
	private DatiEdificio edificio;
	private Strumenti strumenti;

	public StartingWindow() {

		// ottengo dimensioni schermo
		Rectangle maxBounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
		height = maxBounds.height;
		width = maxBounds.width;
		window.setSize(width, height - 30);
		window.setIconImage(new ImageIcon(ClassLoader.getSystemResource("icon.jpg")).getImage());
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		avvio();

		setProjectList();

		apri.setIcon(new ImageIcon(ClassLoader.getSystemResource("apri.png")));
		apri.setContentAreaFilled(false);
		apri.setRolloverEnabled(true);
		apri.setRolloverSelectedIcon(new ImageIcon(ClassLoader.getSystemResource("apri_roll.png")));
		apri.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("apri_roll.png")));
		apri.setPreferredSize(new Dimension(width / 4, 25));

		menubar.add(apri);
		menubar.setPreferredSize(new Dimension(width, 40));
		window.setJMenuBar(menubar);

		nuovo();

		projectPanel.setLayout(new MigLayout());
		projectPanel.setPreferredSize(new Dimension(width, height));

		projectPanel.add(tab, "dock north ,gapleft 5, width " + width * 9.4 / 10 + ":" + width * 9.4 / 10 + ":" + width * 9.4 / 10 + ",height "
				+ height * 8 / 10 + ":" + height * 8 / 10 + ":" + height * 8 / 10);
		// tab.setPreferredSize(new Dimension(width, height * 8 / 10));
		window.setContentPane(tab);

		addOption();

		refresh();

		window.setVisible(true);
	}

	/**
	 * crea cartella di sistema
	 */
	void avvio() {
		// accesso alla cartella di sistema, cancella quanto fatto prima
		Properties pc = System.getProperties();
		String homePath = pc.getProperty("user.home");
		File aa = new File(homePath + pc.getProperty("file.separator") + "ArchimedeSuper");
		if (aa.exists())
			try {
				FileUtils.deleteDirectory(aa);
			} catch (IOException e) {
				e.printStackTrace();
			}
		aa.mkdir();
	}

	/**
	 * crea la lista di progetti caricabili nel menu 'Apri progetto'
	 */
	public void setProjectList() {
		// tolgo i valori che c'erano prima
		apri.removeAll();

		// connessione al server
		FTPClient client = new FTPClient();
		try {
			try {
				client.connect("192.168.100.3");
			} catch (Exception esterno) {
				client.connect("83.211.158.68");
			}
			client.login("stefano", "0901");
			client.changeDirectory("java");
			// lista cartelle presenti
			FTPFile[] list = client.list();
			for (int i = 0; i < list.length; i++) {
				// cerco solo le cartelle
				if (list[i].getType() == FTPFile.TYPE_DIRECTORY) {
					// cartelle di progetti non completati -->completato dopo
					// aver fatto il pdf
					if (!list[i].getName().equals("_eliminati")) {
						// aggiungo nel menu il nome del progetto
						JMenuItem tp = new JMenuItem(list[i].getName());
						// System.out.println("<<"+list[i].getName());
						tp.addActionListener(new Open(list[i].getName()));
						apri.add(tp);
					}
				}
			}
			client.logout();
			client.disconnect(true);

		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (FTPIllegalReplyException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (FTPException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (FTPDataTransferException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FTPAbortedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FTPListParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * crea nuovo progetto
	 */
	public void nuovo() {
		// resetto tutti i valori
		tab.removeAll();
		// inizializza nuovi oggetti
		edificio = new DatiEdificio(StartingWindow.this);
		datiEdificio = new BuildingData(StartingWindow.this, edificio);
		premesse = new Premesse(StartingWindow.this);
		rilevazione = new PuntiRilevazione(StartingWindow.this);
		critico = new PuntoCritico(StartingWindow.this);
		piantina = new Piantina(StartingWindow.this);
		sali = new Sali(StartingWindow.this);
		verticali = new PotenzialiVerticali(StartingWindow.this);
		orizzontali = new PotenzialiOrizzontali(StartingWindow.this);
		conclusioni = new Conclusioni(this);
		strumenti = new Strumenti();

		tab.add("Dati edificio", new JScrollPane(edificio, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});
		tab.add("Premesse", new JScrollPane(premesse, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});
		tab.add("Immobile", new JScrollPane(datiEdificio, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});
		tab.add("Strumenti", new JScrollPane(strumenti, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});
		tab.add("Punti misurazione", rilevazione);
		tab.add("Punti critici", critico);
		tab.add("Pianta con punti", new JScrollPane(piantina, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});
		tab.add("Sali", new JScrollPane(sali, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});
		tab.add("Tensione verticale",
				new JScrollPane(verticali, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
					@Override
					public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
						// TODO Auto-generated method stub
						verticalScrollBar.setUnitIncrement(15);
						super.setVerticalScrollBar(verticalScrollBar);
					}
				});

		tab.add("Tensione orizzontale", new JScrollPane(orizzontali, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});
		tab.add("Conclusioni", new JScrollPane(conclusioni, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
			@Override
			public void setVerticalScrollBar(JScrollBar verticalScrollBar) {
				// TODO Auto-generated method stub
				verticalScrollBar.setUnitIncrement(15);
				super.setVerticalScrollBar(verticalScrollBar);
			}
		});

		window.setTitle("EUREKA - ARCHIMEDE" + " ~ Progetto " + countRtd);
	}

	/**
	 * metodo ausiliario per ridisegnare la finestra
	 */
	public void refresh() {
		window.paintAll(window.getGraphics());
	}

	/**
	 * aggiunge azioni ai pulsanti
	 */
	public void addOption() {

		// crea pdf salvando in locale i dati, non li invia al server
		JButton pdf = new JButton("PDF", new ImageIcon(ClassLoader.getSystemResource("pdf.png")));
		pdf.setContentAreaFilled(false);
		pdf.setRolloverEnabled(true);
		pdf.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("pdf_roll.png")));
		// invia al server il progetto
		JButton invia = new JButton("INVIA", new ImageIcon(ClassLoader.getSystemResource("invia-file.png")));
		invia.setContentAreaFilled(false);
		invia.setRolloverEnabled(true);
		invia.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("invia-file_roll.png")));
		// cancella progetto dal server(sposta in un'altra directory
		JButton elimina = new JButton("ELIMINA", new ImageIcon(ClassLoader.getSystemResource("elimina-file.png")));
		elimina.setContentAreaFilled(false);
		elimina.setRolloverEnabled(true);
		elimina.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("elimina-file_roll.png")));

		// dimensioni
		pdf.setPreferredSize(new Dimension(width / 4, 25));
		invia.setPreferredSize(new Dimension(width / 4, 25));
		elimina.setPreferredSize(new Dimension(width / 4, 25));

		// invia al server il progetto
		invia.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// salva in locale
				save();
				// connessione server
				FTPClient client = new FTPClient();
				try {
					try {
						client.connect("192.168.100.3");
					} catch (Exception esterno) {
						client.connect("83.211.158.68");
					}
					client.login("stefano", "0901");
					client.changeDirectory("java");
					try {
						client.createDirectory(nameProject);
						// System.out.println(nameProject +
						// " create directory");
					} catch (Exception er) {
						client.deleteDirectory(nameProject);
						client.createDirectory(nameProject);
						// System.out.println(nameProject
						// + " remove e create directory");
					}
					// entra nella directory
					client.changeDirectory(nameProject);

					// carica i file
					Properties pc = System.getProperties();
					String homePath = pc.getProperty("user.home");
					String directoryProject = homePath + pc.getProperty("file.separator") + "ArchimedeSuper" + pc.getProperty("file.separator")
							+ countRtd;
					File dir = new File(directoryProject);
					String[] fileDir = dir.list();
					for (int i = 0; i < fileDir.length; i++) {
						try {
							client.upload(new java.io.File(dir + "/" + fileDir[i]));
							// System.out.println("upload" + fileDir[i]);
						} catch (FTPDataTransferException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (FTPAbortedException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}

					}
					client.logout();
					client.disconnect(true);
					// System.out.println("logout");

					JOptionPane.showMessageDialog(null, "Progetto inviato");
					// FileUtils.deleteDirectory(dir);
				} catch (IllegalStateException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (FTPIllegalReplyException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (FTPException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			}
		});

		// crea il pdf
		pdf.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// salva in locale
				save();
				// crea pdf
				Document document = new Document(PageSize.A4, 45, 45, 80, 30);
				try {
					// seleziona dove salvare pdf
					JFileChooser fc = new JFileChooser();
					fc.setSelectedFile(new File(nameProject+".pdf"));
					int returnVal = fc.showSaveDialog(StartingWindow.this.window);
					if (returnVal == JFileChooser.APPROVE_OPTION) {
						File file = fc.getSelectedFile();
						// This is where a real application would save the file.
						if (!file.getAbsolutePath().endsWith(".pdf")) {

							file = new File(file.getAbsolutePath() + ".pdf");
						}
						PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
						writer.setBoxSize("art", new com.itextpdf.text.Rectangle(26, 44, 559, 788));

						HeaderFooter event = new HeaderFooter();
						writer.setPageEvent(event);

						document.open();
						datiEdificio.PDFintro(document);
						premesse.PDF(document);
						datiEdificio.PDFdati(document);
						strumenti.pdf(document);
						piantina.pdf(document);
						rilevazione.pdf(document);
						sali.pdf(document);
						verticali.pdf(document);
						orizzontali.pdf(document);
						critico.pdf(document);
						conclusioni.pdf(document);
						document.close();

					} else {
						// log.append("Save command cancelled by user." +
						// newline);
					}

				} catch (FileNotFoundException e) {

					e.printStackTrace();
				} catch (DocumentException e) {

					e.printStackTrace();
				}
				// Properties pc = System.getProperties();
				// String homePath = pc.getProperty("user.home");
				// String directoryProject = homePath
				// + pc.getProperty("file.separator") + "ArchimedeSuper"
				// + pc.getProperty("file.separator") + countRtd;
				// new Ftp(directoryProject);
			}
		});

		// elimina il progetto dal server
		elimina.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				int ris = JOptionPane.showConfirmDialog(null, "Vuoi eliminare questo progetto?");
				if (ris == 0) {

					// connetto al server e metto la cartella in _eliminati
					FTPClient client = new FTPClient();

					try {
						try {
							client.connect("192.168.100.3");
						} catch (Exception esterno) {
							client.connect("83.211.158.68");
						}
						client.login("stefano", "0901");
						client.changeDirectory("java");
						// elimino cartella
						client.deleteDirectory(nameProject);

						// copio i file in '_eliminati'
						client.changeDirectory("_eliminati");

						try {
							client.createDirectory(nameProject);
							// System.out.println(nameProject +
							// " create directory");
						} catch (Exception er) {
							client.deleteDirectory(nameProject);
							client.createDirectory(nameProject);
							// System.out.println(nameProject
							// + " remove e create directory");
						}
						// entra nella directory
						client.changeDirectory(nameProject);

						// carica i file
						Properties pc = System.getProperties();
						String homePath = pc.getProperty("user.home");
						String directoryProject = homePath + pc.getProperty("file.separator") + "ArchimedeSuper" + pc.getProperty("file.separator")
								+ countRtd;
						File dir = new File(directoryProject);
						String[] fileDir = dir.list();
						for (int i = 0; i < fileDir.length; i++) {
							try {
								client.upload(new java.io.File(dir + "/" + fileDir[i]));
								// System.out.println("upload" + fileDir[i]);
							} catch (FTPDataTransferException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							} catch (FTPAbortedException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}

						}

						client.logout();
						client.disconnect(true);

						// resetta tutto
						nuovo();
						setProjectList();

						// elimino localmente la cartella scaricata
						try {
							FileUtils.deleteDirectory(dir);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (FTPIllegalReplyException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (FTPException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

			}
		});

		menubar.add(new JSeparator(SwingConstants.VERTICAL));
		// menubar.add(save);
		menubar.add(new JSeparator(SwingConstants.VERTICAL));
		menubar.add(pdf);
		menubar.add(new JSeparator(SwingConstants.VERTICAL));
		menubar.add(invia);
		menubar.add(new JSeparator(SwingConstants.VERTICAL));
		menubar.add(elimina);
	}

	/**
	 * salvare i dati del progetto corrente in locale
	 */
	public void save() {
		// leggo file rtd
		Properties pc = System.getProperties();
		String homePath = pc.getProperty("user.home");

		String directoryProject = homePath + pc.getProperty("file.separator") + "ArchimedeSuper" + pc.getProperty("file.separator") + countRtd;
		File fileSave = new File(directoryProject + pc.getProperty("file.separator") + countRtd + ".txt");
		try {
			fileSave.setWritable(true);
			FileWriter fw = new FileWriter(fileSave);
			BufferedWriter bw = new BufferedWriter(fw);
			PrintWriter outFile = new PrintWriter(bw);

			String print = datiEdificio.print();
			print = print + premesse.print();
			print = print + strumenti.print();
			print = print + rilevazione.print();
			print = print + critico.print();
			print = print + sali.print();
			print = print + conclusioni.print();
			print = print + piantina.print();
			print = print + verticali.print();
			print = print + orizzontali.print();
			outFile.println(print);

			outFile.close();
			fileSave.setReadOnly();
			fileSave.setWritable(false);

			// salvo foto piantine
			try {
				piantina.save();

			} catch (Exception ex) {
				JOptionPane.showMessageDialog(null, "Riprova");
				ex.printStackTrace();
			}

		} catch (FileNotFoundException e1) {

			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * classe interna per aprire il progetto selezionato a caricare i dati salvati
	 * 
	 * @author Alex
	 * 
	 */
	class Open implements ActionListener {
		private int n;
		private String progetto;

		Open(String name) {
			progetto = name;
			try {
				n = Integer.parseInt(name.substring(0, 3));
			} catch (Exception e) {
				try {
					n = Integer.parseInt(name.substring(0, 2));
				} catch (Exception e2) {
					try {
						n = Integer.parseInt(name.substring(0, 1));
					} catch (Exception e3) {
						// TODO: handle exception
					}
				}
			}

			// System.out.println("addActionListener " + n);
		}

		public void actionPerformed(ActionEvent e) {
			countRtd = n;
			nameProject = progetto;
			// reset dati precedenti
			nuovo();
			// caricamento file
			FTPClient client = new FTPClient();
			try {

				try {
					client.connect("192.168.100.3");
				} catch (Exception esterno) {
					client.connect("83.211.158.68");
				}
				client.login("stefano", "0901");
				client.changeDirectory("java");

				// System.out.println(progetto);
				client.changeDirectory(progetto);

				Properties pc = System.getProperties();
				String homePath = pc.getProperty("user.home");
				String directoryProject = homePath + pc.getProperty("file.separator") + "ArchimedeSuper" + pc.getProperty("file.separator")
						+ countRtd;

				String filePath = directoryProject + pc.getProperty("file.separator") + countRtd + ".txt";

				File dirtmp = new File(directoryProject);

				if (dirtmp.exists()) {
					FileUtils.deleteDirectory(dirtmp);
				}
				dirtmp.mkdir();

				// download
				try {
					System.out.println("ok");
					FTPFile[] list = client.list();
					for (int i = 0; i < list.length; i++) {
						// System.out.println(list[i].getName());
						client.download(list[i].getName(), new File(directoryProject + pc.getProperty("file.separator") + list[i].getName()));

					}
					// op.showMessageDialog(null, "DOWNLOAD TERMINATO");
				} catch (Throwable e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				}

				client.logout();
				client.disconnect(true);
				// System.out.println("logout");

				File toScan = new File(filePath);
				Scanner c;
				try {
					c = new Scanner(toScan);
					int index = 0;
					String done = "";
					while (c.hasNextLine()) {
						String tmp = c.nextLine();
						if (tmp.contains("@@")) {
							// System.out.println("done ActionListener " + done
							// +
							// "\t"
							// + index);
							setField(index, done);
							done = "";
							index++;

						} else
							done = done + "\n" + tmp;
						// else
					}

				} catch (FileNotFoundException e1) {

					e1.printStackTrace();
				}

			} catch (IllegalStateException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			} catch (IOException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			} catch (FTPIllegalReplyException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			} catch (FTPException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}

		}

		public void setField(int index, String content) {
			if (index == 0)
				datiEdificio.setFields(content);
			else if (index == 1)
				premesse.setElement(content);
			else if (index == 2)
				strumenti.setElement(content);
			else if (index == 3)
				rilevazione.setElement(content);
			else if (index == 4)
				critico.setElement(content);
			else if (index == 5)
				sali.setElement(content);
			else if (index == 6)
				conclusioni.setElement(content);
			else if (index == 7)
				conclusioni.setProfessionista(content);

			else if (index == 8)
				piantina.setElement(content);
			else if (index == 9)
				verticali.setElement(content);
			else if (index == 10)
				orizzontali.setElement(content);
		}
	}

	/**
	 * classe interna per creare intestazione e fronte e pie di pagina
	 * 
	 * @author tomaseo
	 * 
	 */
	class HeaderFooter extends PdfPageEventHelper {
		/** The header text. */
		String header;
		/** The template with the total number of pages. */
		PdfTemplate total;

		/**
		 * Allows us to change the content of the header.
		 * 
		 * @param header The new header String
		 */
		public void setHeader(String header) {
			this.header = header;
		}

		/**
		 * Creates the PdfTemplate that will hold the total number of pages.
		 * 
		 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
		 */
		public void onOpenDocument(PdfWriter writer, Document document) {
			total = writer.getDirectContent().createTemplate(30, 16);
		}

		/**
		 * Adds a header to every page
		 * 
		 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
		 */
		public void onEndPage(PdfWriter writer, Document document) {

			if (writer.getPageNumber() != 1) {
				PdfPTable table = new PdfPTable(1);
				try {
					table.setWidths(new int[] { 24 });
					table.setTotalWidth(527);
					table.setLockedWidth(true);
					com.itextpdf.text.Image img = com.itextpdf.text.Image.getInstance(ClassLoader.getSystemResource("logo_eureka.jpg"));
					img.setCompressionLevel(9);
					img.scaleToFit(184, 65);

					PdfPCell cell = new PdfPCell(img);
					// cell.setBorder(Rectangle.BOTTOM);
					cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
					cell.setBorder(PdfPCell.NO_BORDER);
					table.addCell(cell);
					table.writeSelectedRows(0, -1, -315, 833, writer.getDirectContent());
				} catch (DocumentException de) {
					throw new ExceptionConverter(de);
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				com.itextpdf.text.Rectangle rect = writer.getBoxSize("art");
				ColumnText
						.showTextAligned(
								writer.getDirectContent(),
								Element.ALIGN_CENTER,
								new Phrase(
										"Archimede Group Sas        via F.Tasca,117        35010 S.Pietro in Gu (PD)        P.I. & Cod. Fisc.:04613330283        R.E.A.:PD404321\nTel 049-7423009                         www.ArchimedeSupergroup.eu                 info@ArchimedeSupergroup.eu",
										FontFactory.getFont(FontFactory.HELVETICA, 8, new BaseColor(0, 102, 255))),
								(rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 12, 0);
				ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
						new Phrase("Tel 049-7423009                            www.archimedegroup.eu                    info@archimedegroup.eu",
								FontFactory.getFont(FontFactory.HELVETICA, 8, new BaseColor(0, 102, 255))), (rect.getLeft() + rect.getRight()) / 2,
						rect.getBottom() - 23, 0);
				ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
						new Phrase("pag. " + writer.getPageNumber(), FontFactory.getFont(FontFactory.HELVETICA, 8, BaseColor.BLACK)),
						rect.getRight(), rect.getBottom() - 23, 0);
			} else {

				com.itextpdf.text.Rectangle rect = writer.getBoxSize("art");
				ColumnText
						.showTextAligned(
								writer.getDirectContent(),
								Element.ALIGN_CENTER,
								new Phrase(
										"Della presente relazione tecnica ne e' vietata la riproduzione, anche parziale, senza l'autorizzazione di ArchimedeSuper Group",
										FontFactory.getFont(FontFactory.HELVETICA, 8, new BaseColor(0, 102, 255))),
								(rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 12, 0);
			}
		}

		/**
		 * Fills out the total number of pages before the document is closed.
		 * 
		 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
		 */
		public void onCloseDocument(PdfWriter writer, Document document) {
			ColumnText.showTextAligned(total, Element.ALIGN_LEFT, new Phrase(String.valueOf(writer.getPageNumber() - 1)), 2, 2, 0);
		}
	}

	/**
	 * @param path :percorso assoluto dell'ultimo file caricato
	 */
	public void setPath(String path) {
		lastPath = path;
	}

	/**
	 * 
	 * @return percorso assoluto dell'ultimo file caricato
	 */
	public String getPath() {
		return lastPath;
	}

	/**
	 * 
	 * @return larghezza schermo
	 */
	public int getWidth() {
		return width;
	}

	/**
	 * 
	 * @return altezza schermo
	 */
	public int getHeight() {
		return height;
	}

	/**
	 * 
	 * @return valore rtd corrente
	 */
	public int getCount() {
		return countRtd;
	}

	/**
	 * main
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		try {
			// Set System L&F
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (UnsupportedLookAndFeelException e) {
			// handle exception
		} catch (ClassNotFoundException e) {
			// handle exception
		} catch (InstantiationException e) {
			// handle exception
		} catch (IllegalAccessException e) {
			// handle exception
		}
		new StartingWindow();
	}

}